package com.lc.luzhengtang.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.ConfirmList_BuyRightNowAdapter;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.conn.ConnBuyNow2;
import com.lc.luzhengtang.conn.ConnPay;
import com.lc.luzhengtang.conn.ConnSubmitOrder;
import com.lc.luzhengtang.event.EventBus;
import com.lc.luzhengtang.event.Info;
import com.lc.luzhengtang.event.Info_Coupon;
import com.lc.luzhengtang.event.Info_Liuyan;
import com.lc.luzhengtang.util.AuthResult;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.util.OrderInfoUtil2_0;
import com.lc.luzhengtang.util.PayResult;
import com.lc.luzhengtang.util.WxPay;
import com.zcx.helper.http.AsyCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.os.Build.VERSION_CODES.N;
import static com.lc.luzhengtang.R.id.img_address_add;
import static com.lc.luzhengtang.R.id.text_tel;
import static com.lc.luzhengtang.R.id.text_text_shop;
import static com.lc.luzhengtang.R.id.text_yunfei;


/**
 * Created by Administrator on 2017/6/12.
 */
public class ConfirmOrderActivity2 extends BaseActivity {


    private static final String TAG = "ConfirmOrderActivity2";
    ConfirmList_BuyRightNowAdapter confirmListAdapter;

    List<ConnBuyNow2.Info.Goods> confirmlist;
    @BindView(R.id.img_news)
    ImageView imgNews;

    @BindView(R.id.text_wulaoer)
    TextView textWulaoer;
    @BindView(R.id.text_tel)
    TextView textTel;
    @BindView(R.id.layout_choose_address)
    LinearLayout layoutChooseAddress;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.text_money)
    TextView textMoney;
    @BindView(R.id.text_text_shop)
    TextView textTextShop;

    @BindView(R.id.layout_wx)
    LinearLayout layoutWx;
    @BindView(R.id.layout_alipay)
    LinearLayout layoutAlipay;
    @BindView(R.id.layout_yue)
    LinearLayout layoutYue;
    @BindView(R.id.layout_xianxia)
    LinearLayout layoutXianxia;
    @BindView(R.id.text_daifu)
    TextView textDaifu;
    @BindView(R.id.img_wx)
    ImageView imgWx;
    @BindView(R.id.img_alipay)
    ImageView imgAlipay;
    @BindView(R.id.img_yue)
    ImageView imgYue;
    @BindView(R.id.img_offline)
    ImageView imgOffline;
    @BindView(R.id.text_allmoney)
    TextView textAllmoney;
    @BindView(R.id.text_address)
    TextView textAddress;

    BigDecimal bd;

    String Allmoney;
    String str_json;

    @BindView(R.id.submit_order)
    Button submitOrder;
    @BindView(R.id.layout_switch_address)
    LinearLayout layoutSwitchAddress;
    @BindView(R.id.text_title)
    TextView textTitle;
    @BindView(R.id.layout_liuyan)
    LinearLayout layoutLiuyan;
    @BindView(R.id.maijia_liuyan)
    TextView maijiaLiuyan;
    @BindView(R.id.layout_coup)
    LinearLayout layoutCoup;
    @BindView(R.id.layout_add_address)
    LinearLayout layoutAddAddress;
    @BindView(R.id.text_score)
    TextView textScore;
    @BindView(R.id.text_yunfei)
    TextView textYunfei;
    @BindView(R.id.img_address_add)
    CheckBox imgAddressAdd;
    @BindView(R.id.text_balance)
    TextView textBalance;
    @BindView(R.id.text_coup_money)
    TextView textCoupMoney;

    private String member_id;
    //地址
    private String address;
    //用户收货姓名
    private String username;
    //收货人的手机号
    private String mobile;
    //收货人的城市
    private String city;
    //总运费
    private String postage;
    // 商品的总钱数
    private String totalmoney;
    //  商品的数量
    private String goodsamount;
    //   积分
    private String integral = "2";
    //留言你好，我留言",     留2
    private String String_content = "";
    //优惠券的id
    private String coupon_id;
    //订单号
    private String ordersn;
    //购物车IDs
    private String ids;
    String str_pinjie;
    //    String json = "{'name':'reiz'}";
    JSONObject jsonObj;
    public String data;
    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJVxm7ggLNGRIY3Yt3xoZjrwMzTBCYqM/6X0MiHTds0Ba81dP7LnEBG8tBnc9NV2zWPCOXdPnrN7iGuWxC70C0fhbRPARDRUrbUZqExIeF6UDr6SumGIZZsLoQYobtZxfMXQAQaSgB6/ejbwqY1saHwo7AbG3nMXT7N8m+4p4V0ZAgMBAAECgYBtms88scxtP2Y+pI2eXutrmrPToyieR19QldMW4AMnxD0Od6+6RKGSgLYOqfGfheyJl++RxAF/XcDmN8NXNIH4ZovJLaxLGh44bG9d2MGAApBFbWLM4ZiJ9uK5KyIYztDuYkEicBkHGSe6YtNMe3lX3cTMPMPpHTyODRWitQI7SQJBAPK5eFQf8CXWRZtvv7cwdRjwY4/SGh4Fh25ZwUeizn4/EnZl/XMmYnLVdhQn6sFo5YxC4FJD3vRD0pvXu5lrUNsCQQCdng8+plLI4k7v3lB32Oyv1Xwu/q3CDh9QN9AMKk/5aPD/YrQ9mC6VfQNb5UR30P0/t+SAIOa5/3j9opH4lGIbAkEAjxnF1WMXBFe1phRWJTyObOuc5zfpafW8iNSl3QQhVdD9o4wxxufEdwtemDeIcgrT+sOa2SVmlwA9dN/VnHfmrQJAU+JuHJqqTm1bM3/u9YnGleIZoG08jp2zfp7lo8PVIlj+gfzHDkzy5e5NnlfLc7UPQx0ciDB6ex0DCIHADDr0ZwJBAO4ooeZitqD10l6p7pgP2qz+BYyug+/wJHNpZ2dF12Jp8m6KpD46XK6AvzyOT3HXEoQOmtMABBPktUfEHBELR/A=";
    public static final String APPID = "2017051007189568";
    public static final String RSA2_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private List<ConnBuyNow2.Info.Address> maddres = new ArrayList<>();

    private String order_num;

    String title;
    private String mSum;
    //商品的数量
    private String num_shop;

    private String paytype = "2";

    String getAllmoney;

    String score = "";


    String getPostage;
    BigDecimal bd2;

    String goodsmoney;
    //余额
    String myBanance;


    String str_money_wei;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirmorder);
        EventBus.getInstance().register(this);
        ButterKnife.bind(this);
        rvList.setLayoutManager(new LinearLayoutManager(this));
        confirmlist = new ArrayList<>();
//        ids=getIntent().getStringExtra("cart_id");
        //购物车id
        imgWx.setImageResource(R.mipmap.checkboxselected);
        ids = getIntent().getStringExtra("cart_id");
//        getIntentMoney = getIntent().getStringExtra("bd");
//        num_shop = getIntent().getStringExtra("num_shop");
//        Toast.makeText(context,num_shop, Toast.LENGTH_SHORT).show();
        textTitle.setText("确认订单");
        initData();
//        getOrderData();
    }


    public void initData() {
        new ConnBuyNow2(BaseApplication.basePreferences.readUid(), ids, getIntent().getStringExtra("num"), "盒", new AsyCallBack<ConnBuyNow2.Info>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                showLoading();
            }

            @Override
            public void onSuccess(String toast, int type, Object o, final ConnBuyNow2.Info info) throws Exception {
                super.onSuccess(toast, type, o, info);
                if (info.code == 200) {


                    confirmlist = info.goods;
                    confirmListAdapter = new ConfirmList_BuyRightNowAdapter(confirmlist);
                    rvList.setAdapter(confirmListAdapter);
                    maddres = info.address;
                    title = info.address.get(0).ordersn;
//收货地址
                    address = info.address.get(0).city + info.address.get(0).address;
                    //收货人的姓名
                    username = info.address.get(0).username;
//收货人的手机号

                    Log.d(getPostage, "88888888888888888");
//余额

                    getPostage = info.address.get(0).postage + "";
                    Log.d(getPostage, "88888888888888888");
                    Log.d(getPostage, "88888888888888888");
                    Log.d(getPostage, "88888888888888888");
                    Log.d(getPostage, "88888888888888888");
                    goodsmoney = info.address.get(0).zonggoodsmoney;
                    if (username.isEmpty()) {
                        layoutAddAddress.setVisibility(View.VISIBLE);
                        layoutChooseAddress.setVisibility(View.GONE);
                    } else {
                        layoutAddAddress.setVisibility(View.GONE);
                        layoutChooseAddress.setVisibility(View.VISIBLE);
                    }


                    Double d1 = Double.valueOf(info.address.get(0).zonggoodsmoney);

                    Double c1 = Double.valueOf(getPostage);
                    Double f1 = d1 + c1;
                    String string1 = String.valueOf(f1);
                    bd = new BigDecimal(string1);
                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

//                    Double aDouble = Arith.add(Double.valueOf(info.address.get(0).zonggoodsmoney), Double.valueOf(getPostage));

//                String result = String.format("%.2f");
                    getAllmoney = bd.toString();
                    str_money_wei = bd.toString();
                    textAllmoney.setText("¥" + getAllmoney + "");
                    getAddress = info.address.get(0).username;
                    mobile = info.address.get(0).mobile;
//收货人的城市
                    city = info.address.get(0).city;
                    //总运费


                    myBanance = info.address.get(0).balance;


                    textBalance.setText("（" + "¥" + myBanance + "）");

                    num_shop = info.goods.get(0).number;
                    //留言
                    score = String.valueOf(Double.valueOf(String.valueOf(info.address.get(0).zongintegralmoney)).intValue());
                    //订单号
                    ordersn = info.address.get(0).ordersn;
//                getAllmoney = Double.valueOf(info.goods.get(0).sales).intValue() * Integer.valueOf(info.goods.get(0).number) + "";

                    textAllmoney.setText("¥" + getAllmoney + "");


                    Double d = Double.valueOf(getAllmoney);
                    int a = info.address.get(0).zongintegral;
                    Double c = Double.valueOf(a) / 100;
                    Double f = d - c;
                    String string = String.valueOf(f);
                    bd = new BigDecimal(string);
                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
//                textAllmoney.setText(string);
//                textAllmoney.setText("￥" + bd.toString());
                    totalmoney = bd.toString();
                    String str2 = String.valueOf(c);
                    bd2 = new BigDecimal(str2);
                    bd2 = bd2.setScale(2, BigDecimal.ROUND_HALF_UP);
                    textScore.setText(info.address.get(0).zongintegral + "" + "积分抵¥" + bd2.toString());
                    textWulaoer.setText(info.address.get(0).username);
                    textTel.setText(info.address.get(0).mobile);
                    textAddress.setText(info.address.get(0).city + info.address.get(0).address);
//                text_text_shop
                    textTextShop.setText("¥" + info.goods.get(0).sales + "");
//                text_yunfei
                    textYunfei.setText("+" + "¥" + getPostage + "");
                    if (info.address.get(0).zongintegral <= 0) {
                  /*  LovelyToast.makeText(ConfirmOrderActivity2.this, "积分为0不能抵现", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);*/
                        imgAddressAdd.setChecked(false);
                        totalmoney = getAllmoney;
                        integral = "2";
                        textAllmoney.setText("￥" + getAllmoney);
                        str_money_wei = getAllmoney;
                    } else {
                        imgAddressAdd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @RequiresApi(api = N)
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (Double.valueOf(getAllmoney).intValue() < 1) {
                                    imgAddressAdd.setChecked(false);
                                    LovelyToast.makeText(ConfirmOrderActivity2.this, "当前积分不可用", 0, LovelyToast
                                            .SUCCESS, LovelyToast.SCALE);
                                } else if (isChecked) {
//                            text_allmoney
                                    if (info.address.get(0).zongintegral <= 0) {
                                        LovelyToast.makeText(ConfirmOrderActivity2.this, "积分为0不能抵现", 0, LovelyToast
                                                .SUCCESS, LovelyToast.SCALE);
                                    } else {
                                        integral = "1";
                                        Double d = Double.valueOf(getAllmoney);
                                        int a = info.address.get(0).zongintegral;
                                        Double c = Double.valueOf(a) / 100;
                                        Double f = d - c;
                                        String string = String.valueOf(f);
                                        bd = new BigDecimal(string);
                                        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
//                                    textAllmoney.setText(string);

                                        int a2 = Double.valueOf(bd.toString()).intValue();
                                        if (a2 > 0) {
                                            textAllmoney.setText("¥" + bd.toString());
                                        } else {
                                            textAllmoney.setText("¥" + "0");
                                        }
                                        getAllmoney = bd.toString();
                                        str_money_wei = getAllmoney;
                                   /* totalmoney = bd.toString();
                                    */
                                    }

                                } else {
                                    integral = "";
//
                                    Double d = Double.valueOf(getAllmoney);
                                    int a = info.address.get(0).zongintegral;
                                    Double c = Double.valueOf(a) / 100;
                                    Double f = d + c;
                                    String string = String.valueOf(f);
                                    bd = new BigDecimal(string);
                                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
//                                    textAllmoney.setText(string);
                                    int a2 = Double.valueOf(bd.toString()).intValue();
                                    getAllmoney = bd.toString();

                                    textAllmoney.setText("¥" + getAllmoney);
                                    str_money_wei = getAllmoney;
                                }
                            }
                        });
                    }
                } else if (info.code == 400) {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, info.message, 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    finish();
                } else {

                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                dismissLoading();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                dismissLoading();
            }
        }
        ).execute(ConfirmOrderActivity2.this, false);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                                Toast.makeText(ConfirmOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                        Intent intent2 = new Intent();
                        intent2.putExtra("ids", "2");
                        intent2.putExtra("ordersn", ordersn);
                        intent2.setClass(ConfirmOrderActivity2.this, OrderAllActivity.class);
                        startActivity(intent2);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Intent intent2 = new Intent();


                        intent2.setClass(ConfirmOrderActivity2.this, OrderAllActivity.class);
                        startActivity(intent2);
                        finish();


                        LovelyToast.makeText(ConfirmOrderActivity2.this, "支付失败", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);

                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(ConfirmOrderActivity2.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(ConfirmOrderActivity2.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    public void getReData() {
        member_id = BaseApplication.basePreferences.readUid();

    }


    @OnClick({R.id.img_news, R.id.text_wulaoer, text_tel, R.id.layout_choose_address, R.id.rv_list, R.id.text_money, text_text_shop, text_yunfei, img_address_add, R.id.layout_wx, R.id.layout_alipay, R.id.layout_yue, R.id.layout_xianxia, R.id.text_daifu, R.id.img_wx, R.id.img_alipay, R.id.img_yue, R.id.img_offline, R.id.submit_order, R.id.layout_switch_address, R.id.layout_liuyan, R.id.layout_coup, R.id.layout_add_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_news:
                finish();
                break;
            case R.id.text_wulaoer:
                break;
            case text_tel:
                break;
            case R.id.layout_choose_address:
                break;
            case R.id.rv_list:
                break;
            case R.id.text_money:
                break;
            case text_text_shop:
                break;
            case text_yunfei:
                break;
            case R.id.layout_wx:
                imgWx.setImageResource(R.mipmap.checkboxselected);
                imgAlipay.setImageResource(R.mipmap.checkboxunselected);
                imgYue.setImageResource(R.mipmap.checkboxunselected);
                imgOffline.setImageResource(R.mipmap.checkboxunselected);
                paytype = "2";
                break;
            case R.id.img_wx:
                imgWx.setImageResource(R.mipmap.checkboxselected);
                imgAlipay.setImageResource(R.mipmap.checkboxunselected);
                imgYue.setImageResource(R.mipmap.checkboxunselected);
                imgOffline.setImageResource(R.mipmap.checkboxunselected);
                paytype = "2";
                break;
            case R.id.layout_alipay:
                paytype = "3";
                imgWx.setImageResource(R.mipmap.checkboxunselected);
                imgAlipay.setImageResource(R.mipmap.checkboxselected);
                imgYue.setImageResource(R.mipmap.checkboxunselected);
                imgOffline.setImageResource(R.mipmap.checkboxunselected);
                break;
            case R.id.img_alipay:
                paytype = "3";
                imgWx.setImageResource(R.mipmap.checkboxunselected);
                imgAlipay.setImageResource(R.mipmap.checkboxselected);
                imgYue.setImageResource(R.mipmap.checkboxunselected);
                imgOffline.setImageResource(R.mipmap.checkboxunselected);
                break;
            case R.id.layout_yue:

                if (Double.valueOf(getAllmoney).intValue() > Double.valueOf(myBanance).intValue()) {
                    paytype = "0";
                } else {
                    paytype = "1";
                }
                imgWx.setImageResource(R.mipmap.checkboxunselected);
                imgAlipay.setImageResource(R.mipmap.checkboxunselected);
                imgYue.setImageResource(R.mipmap.checkboxselected);
                imgOffline.setImageResource(R.mipmap.checkboxunselected);
                break;
            case R.id.img_yue:
                if (Double.valueOf(getAllmoney).intValue() > Double.valueOf(myBanance).intValue()) {
                    paytype = "0";
                } else {
                    paytype = "1";
                }
                imgWx.setImageResource(R.mipmap.checkboxunselected);
                imgAlipay.setImageResource(R.mipmap.checkboxunselected);
                imgYue.setImageResource(R.mipmap.checkboxselected);
                imgOffline.setImageResource(R.mipmap.checkboxunselected);
                break;
            case R.id.layout_xianxia:
                paytype = "4";
                imgWx.setImageResource(R.mipmap.checkboxunselected);
                imgAlipay.setImageResource(R.mipmap.checkboxunselected);
                imgYue.setImageResource(R.mipmap.checkboxunselected);
                imgOffline.setImageResource(R.mipmap.checkboxselected);
                break;
            case R.id.img_offline:
                paytype = "4";
                imgWx.setImageResource(R.mipmap.checkboxunselected);
                imgAlipay.setImageResource(R.mipmap.checkboxunselected);
                imgYue.setImageResource(R.mipmap.checkboxunselected);
                imgOffline.setImageResource(R.mipmap.checkboxselected);
                break;
            case R.id.text_daifu:
                break;
            case R.id.submit_order:
                if (TextUtils.isEmpty(textAddress.getText().toString())) {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, "请选择收货地址", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (paytype.equals("0")) {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, "当前余额不足请选择其他支付方式", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (Double.valueOf(getAllmoney).intValue() < 0) {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, "当前支付金额不满足订单", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    getSubmitData();
                }
                break;

            case R.id.layout_switch_address:
                startActivity(new Intent(ConfirmOrderActivity2.this, AddressManageActivity2.class));
                address = "";
                break;

            case R.id.layout_liuyan:
                startActivity(new Intent(ConfirmOrderActivity2.this, LiuyanActivity.class));
                break;
            case R.id.layout_coup:
                Intent intent = new Intent();
                intent.putExtra("getAllmoney", getAllmoney);
                intent.setClass(ConfirmOrderActivity2.this, CouponActivity2.class);
//                if (str_small.equals("")) {
//                } else if (str_small.equals("0") && Double.valueOf(str_big) <=Double.valueOf(getAllmoney)) {
//                    getAllmoney = str_money_wei;
//                    textAllmoney.setText("¥" + getAllmoney + "");
//                } else if (str_small.equals("0") && Double.valueOf(str_big) > Double.valueOf(getAllmoney)) {
////                    textAllmoney.setText("¥" + getAllmoney);
//                    getAllmoney = str_money_wei;
//                    textAllmoney.setText("¥" + getAllmoney + "");
//                }else {
//
//
//                }
                getAllmoney = str_money_wei;
                startActivity(intent);
//                startActivity(new Intent(ConfirmOrderActivity.this, CouponActivity.class));
                break;
            case R.id.layout_add_address:
                startActivity(new Intent(ConfirmOrderActivity2.this, AddressManageActivity2.class));
                break;
        }
    }

    int balance;

    public void getSubmitData() {
        try {

            jsonObj = new JSONObject();

            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < confirmlist.size(); i++) {
                ConnBuyNow2.Info.Goods goods = confirmlist.get(i);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("goods_id", goods.goods_id);
                //member_id
                jsonObject.put("member_id", goods.member_id);
                //number
                jsonObject.put("number", goods.number);
                //goodsattr
                jsonObject.put("goodsattr", goods.goodsattr);
                //title
                jsonObject.put("title", goods.title);
                //picurl
                jsonObject.put("picurl", goods.picurl);
                //sales
                jsonObject.put("sales", goods.sales);


                jsonArray.put(i, jsonObject);
            }
            //goods
            jsonObj.put("goods", jsonArray);
            //member_id
            jsonObj.put("member_id", BaseApplication.basePreferences.readUid());
            //address
            jsonObj.put("address", address);
            //username
            jsonObj.put("username", username);
            //mobile
            jsonObj.put("mobile", mobile);
            //city
            jsonObj.put("city", city);
            //postage
            jsonObj.put("postage", getPostage);
            //totalmoney
            jsonObj.put("totalmoney", getAllmoney);
            //goodsamount
            jsonObj.put("goodsamount", num_shop);
            //
            //积分使用未使用
            jsonObj.put("integral", integral);
            //content 留言内容
            jsonObj.put("content", String_content);
            //coupon_id 优惠券的ID
            jsonObj.put("coupon_id", getCoupon_id);
            //ordersn
            jsonObj.put("ordersn", ordersn);
            //cart_id
            jsonObj.put("cart_id", ids);
            //countmoney   优惠券得钱
            jsonObj.put("countmoney", str_small);
            //zongintegralmoney 积分
            jsonObj.put("zongintegralmoney", score);
            //paytype 支付方式
            jsonObj.put("paytype", paytype);
//goodsmoney
            jsonObj.put("goodsmoney", goodsmoney);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d(jsonObj.toString(), "8888888888888888888888");
        Log.d(jsonObj.toString(), "8888888888888888888888");
        Log.d(jsonObj.toString(), "8888888888888888888888");

        new ConnSubmitOrder(jsonObj.toString(), new AsyCallBack<CommenBean>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);

                LovelyToast.makeText(ConfirmOrderActivity2.this, commenBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);


                //余额
                if (paytype.equals("0")) {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, "余额不足请到待支付页面支付", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    Intent intent = new Intent();
                    intent.setClass(ConfirmOrderActivity2.this, OrderAllActivity.class);
                    startActivity(intent);
                    finish();
                } else if (paytype.equals("1")) {

                    getoffLine();


                } else if (paytype.equals("2")) {
                    //微信支付

                    WxPay wxPay = new WxPay(ConfirmOrderActivity2.this);

                    Log.d(TAG, "getAllMoney = " + getAllmoney);
                    try {
                        double money = Double.parseDouble(getAllmoney) * 100;
                        wxPay.pay("清君堂", ordersn, subZeroAndDot(String.valueOf(money)), "3");
                        finish();
//                        startActivity(new Intent(ConfirmOrderActivity2.this, OrderAllActivity.class));
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        Toast.makeText(ConfirmOrderActivity2.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                    }

                } else if (paytype.equals("3")) {
                    //支付宝
                    alipayData();
                } else if (paytype.equals("4")) {
                  /*  LovelyToast.makeText(ConfirmOrderActivity2.this, "请去待支付页面去支付", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);*/
                    startActivity(new Intent(ConfirmOrderActivity2.this, OrderAllActivity.class));
                    finish();
                }
//                alipayData();


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }

        ).execute(ConfirmOrderActivity2.this, false);
    }

    /**
     * 使用java正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    private String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }


    //线下
    public void getoffLine() {
        new ConnPay(ordersn, paytype, new AsyCallBack<CommenBean>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                if (commenBean.getCode() == 200) {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    Intent intent2 = new Intent();
                    intent2.putExtra("ids", "2");
                    intent2.putExtra("ordersn", ordersn);
                    intent2.setClass(ConfirmOrderActivity2.this, OrderAllActivity.class);
                    startActivity(intent2);
                    finish();
                } else {
                    LovelyToast.makeText(ConfirmOrderActivity2.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    startActivity(new Intent(ConfirmOrderActivity2.this, OrderAllActivity.class));
                    finish();
                }


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                LovelyToast.makeText(ConfirmOrderActivity2.this, "请到待支付页面支付", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                startActivity(new Intent(ConfirmOrderActivity2.this, OrderAllActivity.class));
                finish();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }


        ).execute(ConfirmOrderActivity2.this, false);


    }

    public void alipayData() {


        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */

        String name = "鹿正堂";
        String body = ordersn + "," + "0" + "," + num_shop + "," + BaseApplication.basePreferences.readUid();
        boolean rsa2 = false;
//        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, body, ordersn, num_shop, name);
        Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, body, ordersn, getAllmoney, name);
        String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);

        String sign = OrderInfoUtil2_0.getSign(authInfoMap, ConfirmOrderActivity.RSA_PRIVATE, rsa2);
        final String authInfo = info + "&" + sign;
        Log.i("123456789", authInfo);
        Runnable authRunable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask对象
                AuthTask authTask = new AuthTask(ConfirmOrderActivity2.this);

                // 调用支付接口,获取支付结果
                Map<String, String> result = authTask.authV2(authInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread authThread = new Thread(authRunable);
        authThread.start();


    }

    public static OnCityChangeCallBack OnCityChangeCallBack;


    public interface OnCityChangeCallBack {

        void onCityChange(String area);

        void onCityChange2(String area2);

        void onCityChange3(String area3);
    }


    public void onEventMain(Info_Liuyan i) {
        Log.i("cky", i.msg);
        maijiaLiuyan.setText(i.msg);
        String_content = i.msg;
    }

    public void onEventMain(String i) {
        Log.i("gantamade", i);
        textWulaoer.setText(i);
    }

    String str_big, str_small = "";
    String getCoupon_id = "";
    //还原以前的money
    String huanyuan;
    Double bDoube;

    public void onEventMain(Info_Coupon i) {
        str_big = i.msg;
        str_small = i.str2;
        getCoupon_id = i.id;
        if (Double.valueOf(getAllmoney).intValue() < Double.valueOf(str_big).intValue()) {
//            textAllmoney.setText("￥" + (Double.valueOf(getAllmoney).intValue() - Double.valueOf(str_small).intValue()) + "");
            str_small = "0";
            LovelyToast.makeText(ConfirmOrderActivity2.this, "该金额不满足优惠券使用", 0, LovelyToast
                    .SUCCESS, LovelyToast.SCALE);

            getCoupon_id = "";
            textCoupMoney.setText("");
            getAllmoney = str_money_wei;
            textAllmoney.setText("￥" + getAllmoney);
        } else if (Double.valueOf(getAllmoney).intValue() >= Double.valueOf(str_big).intValue()) {
            Double d1 = Double.valueOf(getAllmoney);
            Double c1 = Double.valueOf(str_small);
            Double f1 = d1 - c1;
            String string1 = String.valueOf(f1);
            bd = new BigDecimal(string1);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            getAllmoney = bd.toString();
            textAllmoney.setText("￥" + getAllmoney);
            textCoupMoney.setText("满" + str_big + "元减" + str_small + "元");
        } else {
            getAllmoney = str_money_wei;
            textAllmoney.setText("￥" + getAllmoney);
        }

        Log.d(i.msg, "----------------");
        Log.d(i.str2, "----------------");
    }


    String getAddress = "";

    public void onEventMain(Info i) {
        textWulaoer.setText(i.msg);
        textAddress.setText(i.str4 + i.str2);
        address = i.str2;
        username = i.msg;
        textTel.setText(i.str3);
        city = i.str4;
//        text_tel
        layoutAddAddress.setVisibility(View.GONE);
        layoutChooseAddress.setVisibility(View.VISIBLE);


    }
}
